//
//  BarChartViewController.m
//  Stock
//
//  Created by sun black on 11-8-4.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BarChartViewController.h"

@implementation BarChartViewController
@synthesize upDatas;
@synthesize downDatas;
@synthesize stockId;
@synthesize service;
@synthesize serviceType;
@synthesize chartType;
@synthesize graph;
@synthesize xLableTitles;
@synthesize loadingView;


-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    
    [loadingView removeFromSuperview];
    self.loadingView = nil;
    
    NSArray *newData = [aResult objectForKey:@"quotes"];
    int minAmount=0,maxAmount=0;
    for (int i=0;i<[newData count];i++) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        
        NSDictionary *dict = [newData objectAtIndex:i];
        NSMutableDictionary *data = [NSMutableDictionary dictionaryWithDictionary:dict];
        [data setValue:[NSNumber numberWithInt:i] forKey:@"xValue"];
        int amount = [[data objectForKey:@"amount"] intValue];
        if (amount<minAmount) {
            minAmount = amount;
        }
        if (amount>maxAmount) {
            maxAmount = amount;
        }
        
        if (amount>0) {
            [self.upDatas addObject:data];
        }else{
            [self.downDatas addObject:data];
        }
        NSString *xValue = [data objectForKey:@"ticktime"];
        //去掉日期中的年
        NSArray *dates = [xValue componentsSeparatedByString:@"-"];
        NSMutableArray *array = [NSMutableArray arrayWithArray:dates];
        if (array.count>0) {
            [array removeObjectAtIndex:0];
        }
        [self.xLableTitles addObject:[array componentsJoinedByString:@"-"]];
        
        [pool drain];
    }
    //[self buildChartView];
    
    
    CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    
    plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromInt(minAmount) length:CPTDecimalFromInt(maxAmount-minAmount)];
    plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0f) length:CPTDecimalFromInteger([xLableTitles count])];
    
    
    int labelCount=0,length=0;
    if ([xLableTitles count]<=20) {
        length = 3;
        labelCount = [xLableTitles count]/length;
    }else{
        labelCount = 6;
        length = [xLableTitles count]/labelCount;
    }
    
    //坐标
    CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
    axisSet.xAxis.orthogonalCoordinateDecimal = CPTDecimalFromInt(minAmount);
    axisSet.xAxis.majorIntervalLength = CPTDecimalFromInt(length);
    axisSet.xAxis.minorTicksPerInterval = 0;
    NSMutableArray *labels = [NSMutableArray array];
    for (int i=0; i<labelCount+2; i++) {
        NSString *title = @"";
        if ([xLableTitles count]>0 && i*length<=[xLableTitles count]-1) {
            title = [xLableTitles objectAtIndex:i*length];
        }
        CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:title textStyle:axisSet.xAxis.labelTextStyle];
        NSNumber *tickLocation = [NSDecimalNumber numberWithInt:i*length];
		newLabel.tickLocation = [tickLocation decimalValue];
		[labels addObject:newLabel];
		[newLabel release];
    }
	axisSet.xAxis.axisLabels =  [NSSet setWithArray:labels];
    
    axisSet.yAxis.majorIntervalLength = CPTDecimalFromFloat(maxAmount-minAmount+10);
    axisSet.yAxis.minorTicksPerInterval = 0;
    axisSet.yAxis.orthogonalCoordinateDecimal = CPTDecimalFromString(@"0.0");
    
    [self.graph reloadData];
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.upDatas = [NSMutableArray array];
    self.downDatas = [NSMutableArray array];
    self.xLableTitles = [NSMutableArray array];
    self.service = [[[StockChartDataService alloc] initWithDelegate:self] autorelease];
    
    [self buildChartView];
    
    [self loadChartData];
}
-(void)buildChartView{
    CPTXYGraph *barChart = [[CPTXYGraph alloc] initWithFrame:self.view.bounds];
    [barChart applyTheme:[CPTTheme themeNamed:kCPTDarkGradientTheme]];
    
    self.graph = barChart;
    ((CPTGraphHostingView *)self.view).hostedGraph = barChart;
    
    barChart.plotAreaFrame.borderLineStyle = nil;
    barChart.plotAreaFrame.cornerRadius = 0.0f;
    
    barChart.paddingLeft = 0.0f;
    barChart.paddingRight = 0.0f;
    barChart.paddingTop = 0.0f;
    barChart.paddingBottom = 0.0f;
    
    barChart.plotAreaFrame.paddingLeft = 0.0f;
    barChart.plotAreaFrame.paddingRight = 0.0f;
    barChart.plotAreaFrame.paddingTop = 0.0f;
    barChart.plotAreaFrame.paddingBottom = 20.0f;
    
    
    // Axes
    CPTXYAxisSet *xyAxisSet = (id)graph.axisSet;
    CPTXYAxis *xAxis = xyAxisSet.xAxis;
    CPTMutableTextStyle *textStyle = [CPTTextStyle textStyle];
    textStyle.color = [CPTColor whiteColor];
    textStyle.fontSize = 9.0f;
    textStyle.textAlignment = CPTTextAlignmentCenter;
    xyAxisSet.xAxis.labelTextStyle = textStyle;
    xyAxisSet.yAxis.labelTextStyle = textStyle;  
    
    CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
    lineStyle.lineWidth = 1.0f;
    lineStyle.lineColor = [CPTColor darkGrayColor];
    xAxis.axisLineStyle = lineStyle;
    CPTXYAxis *yAxis = xyAxisSet.yAxis;
    yAxis.axisLineStyle = nil;
    
    //CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
    
    CPTBarPlot *upBar = [CPTBarPlot tubularBarPlotWithColor:[CPTColor redColor] horizontalBars:NO];
    upBar.dataSource = self;
    CPTMutableLineStyle *upLineStyle = [upBar.lineStyle mutableCopy];
    upLineStyle.lineColor = [CPTColor blackColor];
    upBar.lineStyle = upLineStyle;
    [upLineStyle release];
    CPTFill *upFill = [[CPTFill alloc] initWithColor:[CPTColor redColor]];
    upBar.fill = upFill;
    [upFill release];
	upBar.barWidth = CPTDecimalFromFloat(1.0f);
    upBar.identifier = @"up";
    [barChart addPlot:upBar];    
    
    //下跌
    
    CPTBarPlot *barPlot = [CPTBarPlot tubularBarPlotWithColor:[CPTColor greenColor] horizontalBars:NO];
    barPlot.dataSource = self;
    CPTMutableLineStyle *downLineStyle = [barPlot.lineStyle mutableCopy];
    downLineStyle.lineColor = [CPTColor blackColor];
    barPlot.lineStyle = downLineStyle;
    [downLineStyle release];
    CPTFill *downFill = [[CPTFill alloc] initWithColor:[CPTColor greenColor]];
    barPlot.fill = downFill;
    [downFill release];
	barPlot.barWidth = CPTDecimalFromFloat(1.0f);
    barPlot.identifier = @"down";
    [barChart addPlot:barPlot];
    
    [barChart release];
    
    [self.view bringSubviewToFront:loadingView];
}

-(void)loadChartData{
    NSString *uri = [NSString stringWithFormat:@"chart/%@?id=%@&t=%@",serviceType,stockId,chartType];
    [service performSelector:@selector(queryChartDataWithUri:) withObject:uri afterDelay:1.0];
}
#pragma mark -
#pragma mark Plot Data Source Methods

-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
    return [plot.identifier isEqual:@"up"]?[upDatas count]:[downDatas count];
}

-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index 
{
    NSDictionary *dataCell = nil;
    NSDecimalNumber *num = nil;
    if ([plot.identifier isEqual:@"up"]) {
        dataCell = [upDatas objectAtIndex:index];
    }else{
        dataCell = [downDatas objectAtIndex:index];
    }
    if (fieldEnum == CPTBarPlotFieldBarLocation) {
        int xValue = [[dataCell objectForKey:@"xValue"] intValue];
        num = (NSDecimalNumber *) [NSDecimalNumber numberWithInt:xValue];
    }else if (fieldEnum == CPTBarPlotFieldBarTip ) {
        int value = [[dataCell objectForKey:@"amount"] intValue];
        num = (NSDecimalNumber *)[NSDecimalNumber numberWithInt:value];
    }
    return num;
}
/*
-(CPTFill *) barFillForBarPlot:(CPTBarPlot *)barPlot recordIndex:(NSNumber *)index; 
{
	return nil;
}
*/

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.upDatas = nil;
    self.downDatas = nil;
    [service cancleAllRequest];
    self.service = nil;
    self.xLableTitles = nil;
    self.loadingView = nil;
    self.graph = nil;
}
-(void)dealloc{
    self.upDatas = nil;
    self.downDatas = nil;
    [service cancleAllRequest];
    self.service = nil;
    self.xLableTitles = nil;
    self.chartType = nil;
    self.serviceType = nil;
    self.stockId = nil;
    self.loadingView = nil;
    self.graph = nil;
    [super dealloc];
}

@end
